<?php

namespace app\admin\controller\facrm\analysis;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;


/**
 *员工分析
 */
class Admin extends Backend
{
    protected $model = null;
    protected $searchFields = 'id,username,nickname';
    protected $groupList=[];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $this->groupList=$groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }
        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);

    }

    /**
     * 客户量分析
     * @return array|bool|string|\think\response\Json
     * @throws \think\Exception
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if ($this->request->param('ajax')) {
                return $this->getOrderEchartData();
            }

            $customerModel = new \app\admin\model\facrm\Customer();
            $contractModel = new \app\admin\model\facrm\Contract();
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->field(['password', 'salt', 'token'], true)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as &$row) {
                //获取新增客户总量
                $row['customer_count'] = $customerModel->where('owner_user_id', $row->id)->count();
                $row['deal_count'] = $customerModel->where('owner_user_id', $row->id)->where('deal_status', 1)->count();//成交客户
                $row['deal_rate'] = ($row['customer_count'] != 0 ? round($row['deal_count'] / $row['customer_count'] * 100, 2) : 0) . "%";//成交率
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $erchart = [
            'order' => $this->getOrderEchartData(false),
        ];
        $this->view->assign([
            'erchart' => $erchart,
        ]);
        return $this->view->fetch();
    }

    /**
     *
     * 跟进分析
     * @return \think\response\Json|void
     */
    public function record()
    {
        if ($this->request->isAjax()) {
            if ($this->request->param('ajax') == 1) {
                return $this->getRecordEchartData();
            } elseif ($this->request->param('ajax') == 2) {
                return $this->getRecordTypeEchartData();
            }

            $recordModel = new \app\admin\model\facrm\Record();
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->field(['password', 'salt', 'token'], true)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as &$row) {
                //跟进总次数
                $row['record_count'] = $recordModel->where('create_user_id', $row->id)->where('types', "customer")->count();
                $row['customer_count'] = $recordModel->where('create_user_id', $row->id)->where('types', "customer")->group('types_id')->count();//跟进客户数
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        $erchart = [
            'order' => $this->getRecordEchartData(false),
            'record' => [
                'data' => $this->getRecordTypeEchartData(false),
            ]
        ];
        $this->view->assign([
            'erchart' => $erchart,
        ]);
        return $this->view->fetch();
    }


    /**
     * 业绩分析
     */
    public function achievement(){

        if ($this->request->isAjax()) {
            if ($this->request->param('ajax')) {
                return $this->getAchievementEchart();
            }
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter_c = [];//合同条件
            $filter_r = [];//回款条件
            $c_where = [];//客户条件
            $clues_w = [];//线索条件
            if (isset($filter['search_time'])) {
                $filter['search_time'] = str_replace(' - ', ',', $filter['search_time']);
                $arr = array_slice(explode(',', $filter['search_time']), 0, 2);
                $clues_w['create_time']=$filter_r['return_time']=$c_where['collect_time']=$filter_c['order_time'] = [ 'between time', $arr];
                unset($filter['search_time']);
                $this->request->get(['filter' => json_encode($filter)]);
            }
            //合同模型
            $contractModel = new \app\admin\model\facrm\Contract();
            $receivablesModel=new \app\admin\model\facrm\contract\Receivables();

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where('id','in',$this->childrenAdminIds)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->field(['password', 'salt', 'token'], true)
                ->where('id','in',$this->childrenAdminIds)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $customerModel = new \app\admin\model\facrm\Customer();
            $cluesModel = new \app\admin\model\facrm\Clues();
            foreach ($list as &$row) {
                $row['contract_count'] = $contractModel->where($filter_c)->where('order_admin_id', $row->id)->where('check_status',2)->count();//合同数量
                $row['contract_money'] = $contractModel->where($filter_c)->where('order_admin_id', $row->id)->where('check_status', 2)->sum('money');//合同金额
                $row['receivables_money'] =  $receivablesModel->where($filter_r)->where('order_admin_id', $row->id)->where('check_status', 2)->sum('money');//收款金额

                //分配客户数量,如果丢公海再领取就会不准
                $collect_count = $customerModel->where('owner_user_id', $row->id)->cache(3600)
                    ->where($c_where)->count();
                //最近分配成交的客户数量.如果是老客户分配就会不准
                $purchase_count = $customerModel->where('owner_user_id', $row->id)->cache(3600)
                    ->where('deal_status', 1)->where($c_where)->count();
                $row['customer_data'] = array(
                    'collect_count' => $collect_count,
                    'purchase_count' => $purchase_count,
                    'percentage' => number_format($collect_count ? ($purchase_count / $collect_count) * 100 : 0, 2) . "%",//成交率
                );
                //线索分析
                $create_count = $cluesModel->where('owner_user_id', $row->id)->cache(3600)
                    ->where($clues_w)->count();
                //转客数量
                $transform = $cluesModel->where('owner_user_id', $row->id)->cache(3600)
                    ->where('status', 1)->where($c_where)->count();



                $row['clues_data'] = array(
                    'create_count' => $create_count,
                    'transform' => $transform,
                    'percentage' => number_format($create_count ? ($transform / $create_count) * 100 : 0, 2) . "%",//转客率
                );


            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $erchart = [
            'achievement' => $this->getAchievementEchart(false),
        ];
        $this->view->assign([
            'erchart' => $erchart,
        ]);
        return $this->view->fetch();
    }

    /**
     * 获取最近增量和成交量
     * @return bool
     */
    private function getOrderEchartData($is_ajax = true)
    {
        $startDate = $this->request->param('start_date', null);
        $endDate = $this->request->param('end_date', null);
        $owner_user_id = $this->request->param('owner_user_id', 0, 'intval');
        $customerModel = new \app\admin\model\facrm\Customer();
        // 生成查询的开始和结束时间，默认取30日
        !is_numeric($startDate) && $starttime = strtotime($startDate);
        !is_numeric($endDate) && $endtime = strtotime($endDate);
        $isnotrangeDate = empty($starttime) && empty($endtime);

        $nearly = '30';
        if ($isnotrangeDate) {
            $endtime = time();
            $nearly -= 1;
            $starttime = strtotime("-{$nearly} day");  // 最近30天日期
        } elseif ($starttime > $endtime) {
            $this->error = '起始时间要小于终止时间';
            return false;
        }
        $totalseconds = $endtime - $starttime;;
        if ($totalseconds > 86400 * 30 * 2) {
            $format = '%Y-%m';
        } else {
            if ($totalseconds > 86400) {
                $format = '%Y-%m-%d';
            } else {
                $format = '%H:00';
            }
        }
        //客户增量
        if ($owner_user_id > 0) {
            $customerModel->where('owner_user_id', $owner_user_id);
        }
        $lists = $customerModel->where('collect_time', 'between time', [$starttime, $endtime])
            ->field('COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(collect_time), "' . $format . '") AS add_date')
            ->group('add_date')
            ->select();
        //客户成交量
        if ($owner_user_id > 0) {
            $customerModel->where('owner_user_id', $owner_user_id);
        }
        $listsd = $customerModel->where('deal_time', 'between time', [$starttime, $endtime])
            ->field('COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(deal_time), "' . $format . '") AS add_date')
            ->group('add_date')
            ->select();


        if ($totalseconds > 84600 * 30 * 2) {
            $starttime = strtotime('last month', $starttime);
            while (($starttime = strtotime('next month', $starttime)) <= $endtime) {
                $column[] = date('Y-m', $starttime);
            }
        } else {
            if ($totalseconds > 86400) {
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("Y-m-d", $time);
                    $time += 86400;
                }
            } else {
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("H:00", $time);
                    $time += 3600;
                }
            }
        }


        $c_count = $d_count = array_fill_keys($column, 0);

        foreach ($lists as $k => $v) {
            $c_count[$v['add_date']] = $v['nums'];//客户增量
        }

        foreach ($listsd as $k => $v) {
            $d_count[$v['add_date']] = $v['nums'];//客户成交量
        }

        $result = [
            'date' => array_keys($c_count),
            'd_count' => array_values($d_count),
            'c_count' => array_values($c_count),
        ];

        $data = [
            'date' => $result['date'],
            'data' => [
                "客户增量" => $result['d_count'],
                "客户成交量" => $result['c_count'],
            ],
        ];
        if ($is_ajax) {
            $this->success('', '', [
                'order' => $data
            ]);
        } else {
            return $data;
        }

    }


    /**
     * 跟进趋势
     * @return bool
     */
    private function getRecordEchartData($is_ajax = true)
    {
        $startDate = $this->request->param('start_date', null);
        $endDate = $this->request->param('end_date', null);
        $owner_user_id = $this->request->param('owner_user_id', 0, 'intval');
        $recordModel = new \app\admin\model\facrm\Record();
        $data=$recordModel->getRecordEchartData($startDate,$endDate,$owner_user_id);
        if ($is_ajax) {
            $this->success('', '', [
                'order' => $data
            ]);
        } else {
            return $data;
        }
    }

    /**
     * 跟进分析
     * @param bool $is_ajax
     * @return mixed
     * @throws \think\Exception
     */
    private function getRecordTypeEchartData($is_ajax = true)
    {
        $startDate = $this->request->param('start_date', null);
        $endDate = $this->request->param('end_date', null);
        $owner_user_id = $this->request->param('owner_user_id', 0, 'intval');
        // 生成查询的开始和结束时间，默认取30日
        !is_numeric($startDate) && $starttime = strtotime($startDate);
        !is_numeric($endDate) && $endtime = strtotime($endDate);

        $config = get_addon_config('facrm');
        $recordModel = new \app\admin\model\facrm\Record();
        foreach ($config['record_type'] as $k => $v) {
            if ($starttime){
                $recordModel->where('create_time', 'between time', [$starttime, $endtime]);
            }
            if ($owner_user_id){
                $recordModel->where('create_user_id',$owner_user_id);
            }
            $r['name'] = $v;
            $r['value'] = $recordModel->where('types', 'customer')->where('record_type', $k)->count();
            $alldata[] = $r;
        }
        if ($is_ajax) {
            $this->success('', '', [
                'record' => $alldata
            ]);
        } else {
            return $alldata;
        }

    }

    /**
     * 业绩分析
     * @param bool $is_ajax
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function  getAchievementEchart($is_ajax = true){
        $startDate = $this->request->param('start_date', null);
        $endDate = $this->request->param('end_date', null);
        $owner_user_id = $this->request->param('owner_user_id', 0, 'intval');
        $group_id = $this->request->param('group_id', 0, 'intval');
        $owner_user_ids=array();
        if ($owner_user_id > 0) {
            $owner_user_ids[]=$owner_user_id;
        }elseif($group_id&&$group_id>0){
            Tree::instance()->init($this->groupList);
            $groupIds=Tree::instance()->getChildrenIds($group_id,true);

            $authGroupList = \app\admin\model\AuthGroupAccess::
            field('uid,group_id')
                ->where('group_id', 'in', $groupIds)
                ->select();

            foreach ($authGroupList as $k => $v) {
                if ($owner_user_ids&&in_array($v['uid'],$owner_user_ids)) continue;
                $owner_user_ids[] = $v['uid'];
            }
            if (!$owner_user_ids){
                $this->error("没有数据");
            }
        }
        $contractModel = new \app\admin\model\facrm\Contract();
        $data=$contractModel->getAchievementEchart($startDate,$endDate,$owner_user_ids);

        if ($is_ajax) {
            $this->success('', '', [
                'achievement' => $data
            ]);
        } else {
            return $data;
        }
    }

}
